<template>
  <div class="categories">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container">
      <div class="addbox">
        <el-button type="primary" @click="addCateVisible = true">添加分类</el-button>
        <!-- 添加分类对话框 -->
        <el-dialog v-model="addCateVisible" title="添加分类">
          <el-form
            :model="addCateFrom"
            :label-width="100"
            class="demo-ruleForm"
            ref="addCateFromref"
            :rules="addrules"
          >
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="addCateFrom.name" type="text" />
            </el-form-item>
            <el-form-item label="父级分类" prop="details">
              <el-cascader
                placeholder="请选择分类"
                v-model="addCateFrom.catename"
                :options="cascader"
                :props="cascaderprops"
                @change="handleChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="addCateVisible = false">取消</el-button>
              <el-button type="primary" @click="addCateOK(addCateFromref)">确定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="titlebox">
        <el-alert
          title="下来的数据只要多一点,eltable就会光速爆炸,渲染巨慢,所以建议一次只看一行,获得流畅体验"
          type="warning"
          effect="dark"
          show-icon
        />
      </div>

      <!-- 表格主体 -->
      <el-table
        :data="CateGoryList"
        style="width: 100%"
        border
        stripe
        size="default"
        row-key="cat_id"
        :load="load"
        lazy
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="index" width="60" />
        <el-table-column prop="cat_name" label="分类名称" />
        <el-table-column prop="cat_deleted" label="是否有效">
          <template #default="scope">
            <el-tag type="success" round effect="dark" v-if="!scope.row.is_ok">有效</el-tag>
            <el-tag type="error" round effect="dark" v-else>无效</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="cat_level" label="排序">
          <template #default="scope">
            <el-tag
              :type="levelfiltertwo[scope.row.cat_level].type"
            >{{levelfiltertwo[scope.row.cat_level].text}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作">
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" @click="edit(scope.row)">
              <el-icon>
                <EditPen />
              </el-icon>编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" @click="deleteThere(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="queryInfo.pagenum"
            v-model:page-size="queryInfo.pagesize"
            :page-sizes="[1,2, 3, 5]"
            layout="total,sizes, prev, pager, next, jumper"
            :total="totals"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </div>
      <!-- 编辑对话框 -->
      <el-dialog v-model="editVisible" title="修改用户信息">
        <el-form
          :model="editFrom"
          :label-width="100"
          class="demo-ruleForm"
          :rules="addrules"
          ref="editFromref"
        >
          <el-form-item label="分类名称" prop="catename">
            <el-input v-model="editFrom.catename" type="text" />
          </el-form-item>
          <el-form-item>
            <el-button @click="editVisible = false">取消</el-button>
            <el-button type="primary" @click="editThere(editFromref)">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onBeforeMount } from "vue";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getCategories,
  deleteCategories,
  postaddCategories,
  puteditCategories
} from "../tools/ajax.js";
import { levelfiltertwo } from "../tools/filiter.js";
const route = useRoute();
const router = useRouter();
const cascaderprops = {
  expandTrigger: "hover",
  label: "cat_name",
  value: "cat_level",
  children: "children",
  emitPath: false
};
const cascader = reactive([]);
const editFromref = reactive({});
const CateGoryList = reactive([]);
const editVisible = ref(false);
const addCateVisible = ref(false);
const editFrom = reactive({
  catename: "",
  id: ""
});
const addCateFromref = reactive({});
const addCateFrom = reactive({
  name: "",
  catename: 0
});
const queryInfo = reactive({
  type: "",
  // 当前页数
  pagenum: 1,
  // 每页显示多少数据
  pagesize: 1
});
const totals = ref(0);
const load = (row, treeNode, resolve) => {
  console.log(row, treeNode);
  if (row.cat_level == 0) {
    row.children.forEach(item => {
      if (item.children.length >= 1) {
        item.hasChildren = true;
        setTimeout(() => {
          resolve(row.children);
        }, 500);
      }
    });
  } else if (row.cat_level == 1) {
    setTimeout(() => {
      resolve(row.children);
    }, 500);
  }
};
const addrules = {
  catesname: [
    {
      required: true,
      message: "分类名称不能为空",
      trigger: "change"
    }
  ],
  name: {
    required: true,
    message: "分类名称不能为空",
    trigger: "change"
  }
};
function getlist() {
  getCategories({ params: queryInfo }).then(res => {
    console.log(res.data);
    totals.value = res.data.total;
    CateGoryList.splice(0, 1000);
    CateGoryList.push(...res.data.result);
    CateGoryList.forEach((item, i) => {
      item.index = i + 1;
      item.hasChildren = true;
    });
  });
}
function getTypeList() {
  getCategories({ params: { type: 2 } }).then(res => {
    console.log(res);
    cascader.splice(0, 1000);
    cascader.push(...res.data);
  });
}
// 修改用户状态
function toAddGoods() {
  router.push("/goods/all");
}
function handleSizeChange() {
  console.log("每页条数改变了");
  getlist();
}
function handleCurrentChange() {
  console.log("翻页了");
  getlist();
}
function search() {
  console.log("搜索执行了");
  getlist();
}

function editThere(from) {
  from.validate(flag => {
    if (flag) {
      console.log(editFrom);
      puteditCategories({
        id: editFrom.id,
        cat_name: editFrom.catename
      }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          ElMessage.success(res.meta.msg);
          editVisible.value = false;
          getlist();
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    } else {
      return;
    }
  });
}
function edit(item) {
  console.log(item);
  editVisible.value = true;
  editFrom.catename = item.cat_name;
  editFrom.id = item.cat_id;
}

// 删除商品
function deleteThere(item) {
  console.log(item.cat_id);
  ElMessageBox.confirm("此操作将永久删除该分类,是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteCategories({ id: item.id }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          getlist();
          ElMessage.success(res.meta.msg);
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    })
    .catch(() => {
      ElMessage.warning("取消删除");
    });
}

function addCateOK(from) {
  from.validate(flag => {
    if (flag) {
      console.log(addCateFrom);
      postaddCategories({
        cat_name: addCateFrom.name,
        roleDesc: addCateFrom.details
      }).then(res => {
        console.log(res);
        if (res.meta.status == 201) {
          ElMessage.success(res.meta.msg);
          getlist();
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
      addCateVisible.value = false;
    } else {
      return;
    }
  });
}
const handleChange = value => {
  console.log(value);
};
onBeforeMount(() => {
  getlist();
  getTypeList();
});
</script>

<style scoped>
.addbox {
  display: flex;
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
}
.titlebox{
  margin-bottom: 30px;
}
</style>